#!/bin/bash

set -e

TOP_DIR=$(cd "$(dirname "$0")"/.. || exit; pwd)
GITHUB_WORKSPACE=$TOP_DIR/build_dir
toolchain_tripe=riscv64-linux-gnu-
ARCH=riscv

function build_kernel()
{
    mkdir -p "$GITHUB_WORKSPACE/rootfs/boot"
    mkdir -p "$GITHUB_WORKSPACE/rootfs/bin"
    mkdir -p "$GITHUB_WORKSPACE/rootfs/lib"
    mkdir -p "$GITHUB_WORKSPACE/rootfs/sbin"

    # build kernel
    # refer to https://wiki.sipeed.com/hardware/zh/lichee/th1520/lpi4a/7_develop_revyos.html
    echo "build kernel"
    cd "$TOP_DIR/thead-kernel"
    make CROSS_COMPILE=${toolchain_tripe} ARCH=${ARCH} revyos_defconfig
    make CROSS_COMPILE=${toolchain_tripe} ARCH=${ARCH} -j$(nproc)
    make CROSS_COMPILE=${toolchain_tripe} ARCH=${ARCH} -j$(nproc) dtbs
    if [ x"$(cat .config | grep CONFIG_MODULES=y)" = x"CONFIG_MODULES=y" ]; then
        sudo make CROSS_COMPILE=${toolchain_tripe}  ARCH=${ARCH} INSTALL_MOD_PATH=${GITHUB_WORKSPACE}/rootfs/ modules_install -j$(nproc)
    fi
    #sudo make CROSS_COMPILE=${toolchain_tripe}  ARCH=${ARCH} INSTALL_PATH=${GITHUB_WORKSPACE}/rootfs/boot zinstall -j$(nproc)

    echo "build perf"
    make CROSS_COMPILE=${toolchain_tripe} ARCH=${ARCH} LDFLAGS=-static NO_LIBELF=1 NO_JVMTI=1 VF=1 -C tools/perf/
    sudo cp -v tools/perf/perf ${GITHUB_WORKSPACE}/rootfs/sbin/perf-thead

    git rev-parse HEAD > kernel-commitid
    sudo cp -v kernel-commitid ${GITHUB_WORKSPACE}/rootfs/boot/

    sudo cp -v arch/riscv/boot/Image ${GITHUB_WORKSPACE}/rootfs/boot/
    sudo cp -v arch/riscv/boot/dts/thead/light-lpi4a.dtb ${GITHUB_WORKSPACE}/rootfs/boot/
    sudo cp -v arch/riscv/boot/dts/thead/light-lpi4a-16gb.dtb ${GITHUB_WORKSPACE}/rootfs/boot/
}

function build_uboot()
{
    # pushd uboot
    cd "$TOP_DIR/thead-u-boot"

    # # 构建16G内存版本使用的uboot
    # make light_lpi4a_16g_defconfig
    # make CROSS_COMPILE=${toolchain_tripe} ARCH=${ARCH} -j$(nproc)
    # find . -name "u-boot-with-spl.bin" | xargs -I{} cp -av {} ${GITHUB_WORKSPACE}/rootfs/u-boot-with-spl-lpi4a-16g.bin
    # make clean
    # 构建8G内存版本使用的uboot
    make light_lpi4a_ohos_defconfig
    make CROSS_COMPILE=${toolchain_tripe} ARCH=${ARCH} -j$(nproc)
    find . -name "u-boot-with-spl.bin" | xargs -I{} cp -av {} ${GITHUB_WORKSPACE}/rootfs/u-boot-with-spl-lpi4a-ohos.bin
}

function build_opensbi()
{
    cd "$TOP_DIR/thead-opensbi"
    make PLATFORM=generic ARCH=${ARCH} CROSS_COMPILE=${toolchain_tripe}
    sudo install -D -p -m 644 build/platform/generic/firmware/fw_dynamic.bin \
    "${GITHUB_WORKSPACE}/rootfs/boot/"
}

build_kernel
build_uboot
build_opensbi

cd "${GITHUB_WORKSPACE}"
tar -zcvf kernel.tar.gz rootfs